<template>
  <div class="create-app-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">创建新应用</h1>
        <p class="page-description">填写应用信息，创建您的AI应用</p>
      </div>
    </div>
    
    <div class="create-app-content">
      <div class="form-container">
        <a-card class="create-form-card" :bordered="false">
          <a-form
            :model="appForm"
            :rules="rules"
            @finish="handleCreateApp"
            @finishFailed="handleCreateFailed"
            layout="vertical"
            class="create-app-form"
          >
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item name="appName" label="应用名称">
                  <a-input
                    v-model:value="appForm.appName"
                    size="large"
                    placeholder="请输入应用名称"
                    :maxlength="50"
                    show-count
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="24">
                <a-form-item name="type" label="应用标签">
                  <a-select
                    v-model:value="appForm.type"
                    size="large"
                    placeholder="请选择应用标签"
                    :options="typeOptions"
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="24">
                <a-form-item name="description" label="应用描述">
                  <a-textarea
                    v-model:value="appForm.description"
                    :rows="4"
                    placeholder="请详细描述您的应用功能、特点和使用场景..."
                    :maxlength="500"
                    show-count
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="24">
                <a-form-item name="systemPrompt" label="系统提示词">
                  <a-textarea
                    v-model:value="appForm.systemPrompt"
                    :rows="6"
                    placeholder="请输入系统提示词，用于指导AI的行为和回答风格..."
                    :maxlength="2000"
                    show-count
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="12">
                <a-form-item name="fileGenType" label="文件生成类型">
                  <a-select
                    v-model:value="appForm.fileGenType"
                    size="large"
                    placeholder="请选择文件生成类型"
                    :options="fileTypeOptions"
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="12">
                <a-form-item name="priority" label="优先级">
                  <a-input-number
                    v-model:value="appForm.priority"
                    size="large"
                    placeholder="请输入优先级"
                    :min="1"
                    :max="100"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              
              <a-col :span="24">
                <a-form-item name="cover" label="应用封面">
                  <div class="icon-upload-container">
                    <a-upload
                      v-model:file-list="fileList"
                      name="cover"
                      list-type="picture-card"
                      class="icon-uploader"
                      :show-upload-list="false"
                      :before-upload="beforeUpload"
                      @change="handleIconChange"
                    >
                      <div v-if="appForm.cover" class="icon-preview">
                        <img :src="appForm.cover" alt="应用封面" />
                      </div>
                      <div v-else class="upload-placeholder">
                        <PlusOutlined />
                        <div class="upload-text">上传封面</div>
                      </div>
                    </a-upload>
                    <div class="upload-tips">
                      <p>建议尺寸：400x300px，支持 JPG、PNG 格式</p>
                    </div>
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
            
            <div class="form-actions">
              <a-space size="large">
                <a-button size="large" @click="handleCancel">
                  取消
                </a-button>
                <a-button
                  type="primary"
                  size="large"
                  html-type="submit"
                  :loading="loading"
                  class="create-button"
                >
                  创建应用
                </a-button>
              </a-space>
            </div>
          </a-form>
        </a-card>
        
        <!-- 预览卡片 -->
        <a-card title="应用预览" class="preview-card" :bordered="false">
          <div class="app-preview">
            <div class="preview-icon">
              <img v-if="appForm.cover" :src="appForm.cover" alt="应用封面" />
              <div v-else class="default-icon">
                <AppstoreOutlined />
              </div>
            </div>
            <div class="preview-info">
              <h3 class="preview-name">{{ appForm.appName || '应用名称' }}</h3>
              <p class="preview-category">{{ getTypeName(appForm.type) || '应用标签' }}</p>
              <p class="preview-description">
                {{ appForm.description || '应用描述将在这里显示...' }}
              </p>
            </div>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, AppstoreOutlined } from '@ant-design/icons-vue'
import { createApp } from '@/api/app'
import type { CreateAppRequest } from '@/types/api'

const router = useRouter()
const loading = ref(false)
const fileList = ref([])

// 表单数据
const appForm = reactive<CreateAppRequest>({
  appName: '',
  cover: '',
  systemPrompt: '',
  type: '',
  description: '',
  fileGenType: '',
  priority: 1
})

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 2, max: 50, message: '应用名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择应用标签', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入应用描述', trigger: 'blur' },
    { min: 10, max: 500, message: '应用描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  systemPrompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 10, max: 2000, message: '系统提示词长度在 10 到 2000 个字符', trigger: 'blur' }
  ],
  fileGenType: [
    { required: true, message: '请选择文件生成类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '优先级范围在 1 到 100', trigger: 'blur' }
  ]
}

// 应用标签选项
const typeOptions = [
  { label: '工具类', value: 'tool' },
  { label: '娱乐类', value: 'entertainment' },
  { label: '教育类', value: 'education' },
  { label: '商务类', value: 'business' },
  { label: '生活类', value: 'lifestyle' }
]

// 文件生成类型选项
const fileTypeOptions = [
  { label: 'Word文档', value: 'word' },
  { label: 'PDF文档', value: 'pdf' },
  { label: 'Excel表格', value: 'excel' },
  { label: 'PowerPoint演示', value: 'ppt' },
  { label: '纯文本', value: 'text' }
]

// 获取标签名称
const getTypeName = (typeValue: string) => {
  const type = typeOptions.find(option => option.value === typeValue)
  return type?.label || typeValue
}



// 图标上传前验证
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传，手动处理
}

// 封面上传处理
const handleIconChange = (info: any) => {
  if (info.file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      appForm.cover = e.target?.result as string
    }
    reader.readAsDataURL(info.file)
  }
}

// 创建应用
const handleCreateApp = async () => {
  try {
    loading.value = true
    const response = await createApp(appForm)
    
    if (response.code === 200) {
      message.success('应用创建成功!')
      router.push('/my-apps')
    } else {
      message.error(response.message || '创建失败')
    }
  } catch (error: any) {
    console.error('创建应用错误:', error)
    message.error(error.message || '创建失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 创建失败处理
const handleCreateFailed = (errorInfo: any) => {
  console.log('表单验证失败:', errorInfo)
}

// 取消操作
const handleCancel = () => {
  router.back()
}


</script>

<style scoped>
.create-app-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60px 0;
  color: white;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  text-align: center;
}

.page-title {
  font-size: 48px;
  font-weight: 700;
  margin: 0 0 16px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-description {
  font-size: 18px;
  margin: 0;
  opacity: 0.9;
}

.create-app-content {
  max-width: 1200px;
  margin: -40px auto 0;
  padding: 0 24px 60px;
  position: relative;
  z-index: 2;
}

.form-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  align-items: start;
}

.create-form-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.create-app-form {
  padding: 24px;
}

.icon-upload-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.icon-uploader {
  display: inline-block;
}

:deep(.ant-upload-select-picture-card) {
  width: 128px;
  height: 128px;
  border-radius: 12px;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s;
}

:deep(.ant-upload-select-picture-card:hover) {
  border-color: #667eea;
}

.icon-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.upload-placeholder .anticon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.upload-tips {
  color: #666;
  font-size: 12px;
}

.upload-tips p {
  margin: 0;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.create-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s;
}

.create-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.preview-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 24px;
}

.app-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  gap: 16px;
}

.preview-icon {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-icon {
  font-size: 32px;
  color: #ccc;
}

.preview-info {
  width: 100%;
}

.preview-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
}

.preview-category {
  font-size: 14px;
  color: #667eea;
  margin: 0 0 12px 0;
  font-weight: 500;
}

.preview-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
  word-break: break-word;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .form-container {
    grid-template-columns: 1fr;
  }
  
  .preview-card {
    position: static;
  }
}

@media (max-width: 768px) {
  .page-title {
    font-size: 36px;
  }
  
  .page-description {
    font-size: 16px;
  }
  
  .create-app-content {
    padding: 0 16px 40px;
    margin-top: -20px;
  }
  
  .create-app-form {
    padding: 16px;
  }
}

/* 表单样式优化 */
:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #333;
}

:deep(.ant-input),
:deep(.ant-select-selector),
:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s;
}

:deep(.ant-input:focus),
:deep(.ant-select-focused .ant-select-selector),
:deep(.ant-input-affix-wrapper:focus),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

:deep(.ant-card-head-title) {
  font-weight: 600;
  color: #333;
}
</style>